<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { ConsultOrderPreData, PartialConsult } from '@/types/consult'
import {
  getConsultOrderPre,
  createConsultOrder,
  getConsultOrderPayUrl
} from '@/services/consult'
import { useConsultStore } from '@/stores'
import { getPatientDetail } from '@/services/user'
import {
  showToast,
  showConfirmDialog,
  showDialog,
  showLoadingToast
} from 'vant'
import { onBeforeRouteLeave, useRouter } from 'vue-router'

const payInfo = ref<ConsultOrderPreData>() //预支付信息
const store = useConsultStore()
const patientDetail = ref<Patient>() //患者详情
const agree = ref(false)
const show = ref(false) //支付抽屉
/* 支付组件封装
const paymentMethod = ref<0 | 1>() //支付方式，0 微信，1 支付宝 
 */
const loading = ref(false) //支付加载状态
const orderId = ref('') //订单id
const router = useRouter()

type Key = keyof PartialConsult //问诊类型

// 获取支付订单信息
const getOrderPreInfo = async () => {
  if (!store.consult.type) return
  const res = await getConsultOrderPre({
    type: store.consult.type,
    illnessType: store.consult.illnessType
  })
  payInfo.value = res.data
  store.setCoupon(payInfo.value.couponId)
}
// 获取患者详情
const loadData = async () => {
  if (!store.consult.patientId) return //若是不存在患者则返回
  const res = await getPatientDetail(store.consult.patientId)
  patientDetail.value = res.data
}
// 打开弹框
const submit = async () => {
  if (!agree.value) return showToast('请勾选我已同意支付协议')
  // 打开
  try {
    loading.value = true //开启加载
    const res = await createConsultOrder(store.consult)
    orderId.value = res.data.id //记录订单id
    show.value = true //打开抽屉
    store.clear() //清空本地存储的问诊订单信息
  } finally {
    loading.value = false //停止加载
  }
}
// 关闭抽屉
const onClose = () => {
  showConfirmDialog({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelButtonText: '仍要关闭',
    confirmButtonText: '继续支付'
  })
    // 继续支付
    .then(() => {
      // console.log('继续支付')
    })
    // 仍要关闭
    .catch(() => {
      // console.log('仍要关闭')
      orderId.value = '' //取消支付订单id没意义，并且路由跳转前判断订单id没有才跳转
      router.push('/user/consult')
    })
}
// 订单生成后刷新提示
const refreshPage = () => {
  // 问诊信息缺少提示
  const validKeys: Key[] = [
    //利用key进行类型提示
    'type',
    'illnessType',
    'depId',
    'illnessDesc',
    'illnessTime',
    'consultFlag',
    'patientId'
  ]
  const valid = validKeys.every((key) => store.consult[key] !== undefined) // 问诊信息是否缺少
  if (!valid) {
    return showDialog({
      title: '温馨提示',
      message:
        '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付！',
      closeOnPopstate: false //回退，前进不会自动关闭
    }).then(() => {
      router.push('/')
    })
  }
}

/* 
跳转支付，支付组件封装
const pay = async () => {
  if (paymentMethod.value === undefined) return showToast('请选择支付方式')
  // 支付跳转加载需要一直加载
  showLoadingToast({ message: '跳转支付', duration: 0 })
  const res = await getConsultOrderPayUrl({
    orderId: orderId.value,
    paymentMethod: paymentMethod.value,
    payCallback: 'http://localhost:5173/room' // 回跳到问诊室
  })
  //根据支付地址windows打开
  window.location.href = res.data.payUrl
} */

// 路由跳转前钩子函数
onBeforeRouteLeave(() => {
  // console.log(orderId.value)
  if (orderId.value) return false //若是存在订单则不能跳转
})

onMounted(() => {
  refreshPage() //页面渲染(刷新)

  getOrderPreInfo()
  loadData()
})
</script>

// 支付
<template>
  <div class="consult-pay-page" v-if="payInfo">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo?.actualPayment }}元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="'-¥' + payInfo?.couponDeduction" />
      <van-cell title="积分抵扣" :value="'-¥' + payInfo?.pointDeduction" />
      <van-cell title="实付款" :value="'¥' + payInfo?.payment" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell :title="`${patientDetail?.name} | ${patientDetail?.genderValue} | ${patientDetail?.age}岁`"></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <van-submit-bar button-type="primary" :price="payInfo?.actualPayment * 100" button-text="立即支付" text-align="left"
      :loading="loading" @click="submit" />

    <cp-pay-sheet v-model:show="show" :order-id="orderId" :actualPayment="payInfo.actualPayment" :onClose="onClose" pay-callback="/room"/>

    <!-- 立即支付,封装支付抽屉组件统一使用-->
    <!-- <van-action-sheet
      v-model:show="show"
      title="选择支付方式"
      :close-on-popstate="false"
      :close-on-click-overlay="false"
      :closeable="false"
      @click-overlay="onClose"
    >
      <div class="pay-type">
        <p class="amount">￥{{ payInfo?.actualPayment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="paymentMethod = 0">
            <template #icon><cp-icon name="consult-wechat" /></template>
            <template #extra
              ><van-checkbox :checked="paymentMethod === 0"
            /></template>
          </van-cell>
          <van-cell title="支付宝支付" @click="paymentMethod = 1">
            <template #icon><cp-icon name="consult-alipay" /></template>
            <template #extra
              ><van-checkbox :checked="paymentMethod === 1"
            /></template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button type="primary" round block @click="pay"
            >立即支付</van-button
          >
        </div>
      </div>
    </van-action-sheet> -->
  </div>
  <div class="consult-pay-page" v-else>
    <cp-nav-bar title="支付"></cp-nav-bar>
    <!-- 骨架屏组件 -->
    <van-skeleton title :row="10" style="margin-top:18px"></van-skeleton>
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}

.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;

  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }

  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }

  .desc {
    flex: 1;

    >span {
      display: block;
      color: var(--cp-tag);

      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}

.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }

    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}

.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}

.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;

  .text {
    color: var(--cp-primary);
  }
}

::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}


</style>
